package com.xcw.jac;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class GenerateColorfulImageWithQRCode {

    public static void main(String[] args) {

        int width = 500; // 图片宽度
        int height = 500; // 图片高度

        // 创建BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取Graphics2D对象
        Graphics2D graphics2D = image.createGraphics();

        // 设置背景颜色
        graphics2D.setColor(Color.WHITE);
        graphics2D.fillRect(0, 0, width, height);

        // 生成炫彩图片
        Random random = new Random();
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                int r = random.nextInt(256);
                int g = random.nextInt(256);
                int b = random.nextInt(256);
                graphics2D.setColor(new Color(r, g, b));
                graphics2D.drawLine(i, j, i, j);
            }
        }

        // 释放资源
        graphics2D.dispose();

        // 保存图片
        try {
            File imageFile = new File("colorful_image.png");
            ImageIO.write(image, "png", imageFile);
            System.out.println("Colorful image saved successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 生成二维码
        String qrCodeText = "https://www.example.com";
        int qrCodeSize = 250;

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix;
        try {
            bitMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize,
                    java.util.Collections.singletonMap(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H));

            BufferedImage qrCodeImage = new BufferedImage(qrCodeSize, qrCodeSize, BufferedImage.TYPE_INT_RGB);
            qrCodeImage.createGraphics();

            // 设置二维码颜色
//            graphics2D.setColor(Color.BLACK);
            for (int i = 0; i < qrCodeSize; i++) {
                for (int j = 0; j < qrCodeSize; j++) {
                    if (bitMatrix.get(i, j)) {
                        graphics2D.fillRect(i, j, 1, 1);
                    }
                }
            }

            // 保存二维码图片
            try {
                File qrCodeFile = new File("qr_code.png");
                ImageIO.write(qrCodeImage, "png", qrCodeFile);
                System.out.println("QR code saved successfully!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}